package com.ihrm.system.controller;

import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.utils.JwtUtils;
import com.ihrm.domain.system.Permission;
import com.ihrm.domain.system.User;
import com.ihrm.domain.system.response.ProfileResult;
import com.ihrm.domain.system.response.UserResult;
import com.ihrm.system.service.PermissionService;
import com.ihrm.system.service.UserService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auther chongxiongwei
 * @create 2020-04-17-10:08
 */
@Api(tags = {"用户控制器"})
@CrossOrigin
@RestController
@Slf4j
@RequestMapping("/sys")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private PermissionService permissionService;

    @ApiOperation("上传头像")
    @GetMapping(value = "/user/upload/{id}")
    public Result upload(@PathVariable("id") String id, @RequestParam(name = "file") MultipartFile file) throws IOException {
        String imageUrl = userService.uploadImage(id, file);
        return new Result(ResultCode.SUCCESS, imageUrl);
    }

    /**
     * 分配角色
     * @param
     * @return
     */
    @ApiOperation("分配角色")
    @PutMapping("/user/assignRoles")
    public Result assignRoles(@RequestBody Map<String, Object> map) {
        //1.获取被分配的用户ID
        String userId = (String) map.get("id");
        //2.获取到角色的id列表
        List<String> roleIds = (List<String>) map.get("roleIds");
        //3.调用service完成角色分配
        userService.assignRoles(userId, roleIds);
        return new Result(ResultCode.SUCCESS);
    }

    //保存用户
    @ApiOperation("保存用户")
    @PostMapping("/user")
    public Result save(@RequestBody User user) {
        user.setCompanyId(companyId);
        user.setCompanyName(companyName);
        userService.save(user);
        return new Result(ResultCode.SUCCESS);
    }

    // 根据用户ID 更新用户
    @ApiOperation("根据用户ID更新用户")
    @PutMapping("/user/{id}")
    public Result update(@PathVariable("id") String id, @RequestBody User user) {
        user.setId(id);
        userService.update(user);
        return new Result(ResultCode.SUCCESS);
    }

    // 根据用户ID删除用
    @ApiOperation("根据用户ID删除用户")
    @DeleteMapping("/user/{id}")
    public Result delete(@PathVariable("id") String id) {
        userService.delete(id);
        return new Result(ResultCode.SUCCESS);
    }

    // 根据用户ID查询用户
    @ApiOperation("根据用户ID查找用户")
    @GetMapping("/user/{id}")
    public Result findById(@PathVariable("id") String id) {
        User user = userService.findById(id);
        UserResult userResult = new UserResult(user);
        return new Result(ResultCode.SUCCESS, userResult);
    }

    // 查找全部用户  指定企业id
    @ApiOperation("查找全部用户")
    @GetMapping("/user")
    public Result findAll(int page, int size, @RequestParam(required = false) Map<String, Object> map) {
        map.put("companyId", companyId);
        Page<User> all = userService.findAll(map, page, size);
        PageResult<User> pageResult = new PageResult<User>(all.getTotalElements(), all.getContent());
        return new Result(ResultCode.SUCCESS, pageResult);
    }

    /**
     * 用户登录
     * 1.通过service根据mobile查询用户
     * 2.比较password
     * 3.生成jwt信息
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> map) {

        String mobile = map.get("mobile");
        String password = map.get("password");
        // 1.通过service根据mobile查询用户
        User user = userService.findByMobile(mobile);
        // 2.比较password
        // 登录失败
        if (user == null || !user.getPassword().equals(password)) {
            return new Result(ResultCode.MOBILE_OR_PASS_WORD_ERROR);
        } else {
            // 登录成功
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("companyId", user.getCompanyId());
            userMap.put("companyName", user.getCompanyName());
            // 3.生成jwt信息
            String token = jwtUtils.createJwt(user.getId(), user.getUsername(), userMap);
            return new Result(ResultCode.SUCCESS, token);
        }
    }

    /**
     * 用户登录成功之后获取用户登录信息
     * 1.从Jwt里面获取用户用户ID
     * 2.根据用户ID查询用户
     * 3.构建返回值对象
     * 4.响应数据
     */
    @ApiOperation("用户登录信息")
    @PostMapping("/profile")
    public Result profile(HttpServletRequest request) throws Exception {
        /**
         * 从请求头信息中获取token数据
         *  1. 获取请求头信息：名称=Authorization
         *  2. 替换Bearer+空格
         *  3.解析token获取 claims
         */
        // 1.获取请求头信息：名称=Authorization
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            throw new CommonException(ResultCode.UNAUTHENTICATED);
        }
        // 2.替换Bearer+空格
        String token = authorization.replace("Bearer", "");
        // 3.解析token获取 claims
        Claims claims = jwtUtils.parseJwt(token);
        String userId = claims.getId();
        // 获取用户信息
        User user = userService.findById(userId);
        // 根据不同的用户级别获取用户权限
        ProfileResult result = null;
        // 普通用户直接查询
        if ("user".equals(user.getLevel())) {
            result = new ProfileResult(user);
        } else {
            Map map = new HashMap();
            if ("coAdmin".equals(user.getLevel())) {
                map.put("enVisible", "1");
            }
            log.info("*********level********" + user.getLevel() + "****map***" + map);
            List<Permission> list = permissionService.findAll(map);
            result = new ProfileResult(user, list);
        }
        return new Result(ResultCode.SUCCESS, result);
    }
}
